<template>
  <div class="app-container">

    <!-- 搜索工作栏 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="工厂" prop="factoryId">
        <SelectFactory v-model="queryParams.factoryId"></SelectFactory>
      </el-form-item>
      <el-form-item label="检验单号" prop="code">
        <el-input v-model="queryParams.code" placeholder="请输入检验单号" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="生产工单" prop="moId" v-show="false">
        <el-input v-model="queryParams.moId" placeholder="请输入生产工单" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="生产工单" prop="moCode">
        <el-input v-model="queryParams.moCode" placeholder="请选择生产工单" disabled >
          <el-button slot="append" icon="el-icon-search" @click="openSelectSingleMoQuery = true"></el-button>
        </el-input>
      </el-form-item>
      <el-form-item label="产品信息" prop="itemProduceId" v-show="false">
        <el-input v-model="queryParams.itemProduceId" placeholder="请选择产品信息" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="产品信息" prop="itemCode">
        <el-input v-model="queryParams.itemCode" placeholder="请选择产品信息" disabled >
          <el-button slot="append" icon="el-icon-search" @click="openSelectItemProduce = true"></el-button>
        </el-input>
      </el-form-item>
      <el-form-item label="检测人" prop="userId" v-show="false">
        <el-input v-model="queryParams.userId" placeholder="请输入检测人" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="检测人" prop="userName">
        <el-input v-model="queryParams.userName" placeholder="请选择检测人" disabled >
          <el-button slot="append" icon="el-icon-search" @click="openSelectUser = true"></el-button>
        </el-input>
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker v-model="queryParams.createTime" style="width: 240px" value-format="yyyy-MM-dd HH:mm:ss" type="daterange"
                        range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" :default-time="['00:00:00', '23:59:59']" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                   v-hasPermi="['qms:inspect-process:create']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" :loading="exportLoading"
                   v-hasPermi="['qms:inspect-process:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 列表 -->
    <el-table v-loading="loading" :data="list">
      <el-table-column label="序号" align="center" prop="id" fixed="left" />
      <el-table-column label="检验单号" align="center" prop="code" fixed="left" width="200px" />
      <el-table-column label="工厂" align="center" prop="factoryName" />
      <el-table-column label="检验方案名称" align="center" prop="schemeName" width="150px" />
      <el-table-column label="检验方案代码" align="center" prop="schemeCode" width="150px" />
      <el-table-column label="生产工单" align="center" prop="moCode"  width="200px" />
      <el-table-column label="产品名称" align="center" prop="itemName" width="100px" />
      <el-table-column label="产品代码" align="center" prop="itemCode" width="100px" />
      <el-table-column label="产品规格" align="center" prop="itemSpec" width="100px" show-overflow-tooltip />
      <el-table-column label="产品图号" align="center" prop="drawCode" width="100px"/>
      <el-table-column label="工艺名称" align="center" prop="processName" />
      <el-table-column label="工艺代码" align="center" prop="processCode" />
      <el-table-column label="检验数" align="center" prop="inspectAmount" />
      <el-table-column label="合格数" align="center" prop="qualifiedAmount" />
      <el-table-column label="不合格数" align="center" prop="unqualifiedAmount" />
      <el-table-column label="检测结果" align="center" prop="inspectResult">
        <template v-slot="scope">
          <dict-tag :type="DICT_TYPE.QMS_INSPECT_RESULT" :value="scope.row.inspectResult" />
        </template>
      </el-table-column>
      <el-table-column label="检测人" align="center" prop="userName" width="100px" />
      <el-table-column label="备注" align="center" prop="remark" show-overflow-tooltip />
      <el-table-column label="检测时间" align="center" prop="inspectTime" width="180">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.inspectTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="100px">
        <template v-slot="scope">
        <!-- 暂时关闭修改功能       -->
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['qms:inspect-process:update']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['qms:inspect-process:delete']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>

    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" v-dialogDrag append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="检验单号" prop="code">
              <genCode v-model="form.code" type="inspect" :key="refresh"></genCode>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工厂" prop="factoryName">
              <el-input v-model="form.factoryName" disabled placeholder="请选择工厂"  ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="生产工单" prop="moCode">
              <el-input v-model="form.moCode" placeholder="请选择生产工单" disabled >
                <el-button slot="append" icon="el-icon-search" @click="openSelectSingleMo = true"></el-button>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12"></el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="方案名称" prop="schemeId">
              <el-input v-model="form.schemeName" placeholder="请输入检验方案名称" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="方案代码" prop="schemeId">
              <el-input v-model="form.schemeCode" placeholder="请输入检验方案代码" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="产品名称" prop="itemName" >
              <el-input v-model="form.itemName" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品代码" prop="itemCode" >
              <el-input v-model="form.itemCode" disabled/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="产品规格" prop="itemSpec" >
              <el-input v-model="form.itemSpec" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品图号" prop="drawCode" >
              <el-input v-model="form.drawCode" disabled/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="工艺" prop="processId">
              <el-select v-model="form.processId" placeholder="请选择" @change="changeProcess">
                <el-option v-for="item in form.routes"  :key="item.processId" :label="item.processName" :value="item.processId"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="检验数" prop="inspectAmount">
              <el-input v-model="form.inspectAmount" placeholder="请输入检验数量" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="合格数" prop="qualifiedAmount">
              <el-input v-model="form.qualifiedAmount" placeholder="请输入合格数量" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="不合格数" prop="unqualifiedAmount">
              <el-input v-model="form.unqualifiedAmount" placeholder="请输入不合格数量" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="检测结果" prop="inspectResult">
              <el-select v-model="form.inspectResult" placeholder="请选择检测结果">
                <el-option v-for="dict in inspectOptions"
                           :key="dict.value" :label="dict.label" :value="parseInt(dict.value)" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="检测时间" prop="inspectTime">
              <el-date-picker clearable v-model="form.inspectTime" type="date" value-format="timestamp" placeholder="选择检测时间" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input type="textarea" :autosize="{minRows:2, maxRows:6}" v-model="form.remark" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-table :data="form.entryList" v-loading="load">
              <el-table-column label="检验项目" align="center" prop="entryName" fixed="left" width="150px" />
              <el-table-column label="检验工具" align="center" prop="inspectTools" />
              <el-table-column label="检验方法" align="center" prop="inspectMethod" />
              <el-table-column label="检验标准" align="center" prop="standardStr" />
              <el-table-column label="标准值" align="center" prop="standard" />
              <el-table-column label="误差上限" align="center" prop="standardUp" />
              <el-table-column label="误差下限" align="center" prop="standardDown" />
              <el-table-column label="实际检验值" align="center" prop="reality" width="150px" fixed="right">
                <template v-slot="scope">
                  <el-input type="number" v-model="scope.row.reality" :disabled="scope.row.standard == null || scope.row.standard == undefined" @input="changeReality(scope.row)"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="检验结论" align="center" prop="inspectResult"  width="150px" fixed="right">
                <template v-slot="scope">
                  <el-select v-model="scope.row.inspectResult" placeholder="请选择检测结果">
                    <el-option v-for="dict in inspectOptions"
                               :key="dict.value" :label="dict.label" :value="parseInt(dict.value)" />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="说明" align="center" prop="remark" width="200px" fixed="right">
                <template v-slot="scope">
                  <el-input type="textarea" autosize v-model="scope.row.remark" ></el-input>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 查询生产工单（查询使用） -->
    <SelectSingleMo :openSelectSingleMo.sync="openSelectSingleMoQuery" @selectSingleMo="selectMoQuery"></SelectSingleMo>
    <!-- 查询生产工单（新增使用） -->
    <SelectSingleMo :openSelectSingleMo.sync="openSelectSingleMo" @selectSingleMo="selectMo"></SelectSingleMo>
    <!-- 查询产品生产信息  -->
    <SelectItemProduce :openSelectItemProduce.sync="openSelectItemProduce" @selectItemProduce="selectItemProduce"></SelectItemProduce>

  </div>
</template>

<script>
import { createInspectProcess, updateInspectProcess, deleteInspectProcess, getInspectProcess, getInspectProcessPage, exportInspectProcessExcel } from "@/api/qms/inspectProcess";
import { getInspectSchemeByItem } from "@/api/qms/inspectScheme"
import { getMoInfo } from "@/api/mes/mo"
import SelectFactory from '@/components/SelectFactory/index.vue'
import SelectItemProduce from '@/components/SelectItemProduce/index.vue'
import SelectSingleMo from '@/components/SelectSingleMo/index.vue'
import GenCode from '@/components/GenCode/index.vue'
export default {
  name: "InspectProcess",
  components: {
    GenCode,
    SelectSingleMo,
    SelectFactory,
    SelectItemProduce,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      load: false,
      // 单号刷新
      refresh: undefined,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 过程检验列表
      list: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询生产工单
      openSelectSingleMoQuery: false,
      // 查询生产工单
      openSelectSingleMo: false,
      // 查询产品信息
      openSelectItemProduce: false,
      // 查询工艺信息
      openSelectProcess: false,
      // 查询用户信息
      openSelectUser: false,
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        code: null,
        factoryId: null,
        moId: null,
        moCode: null,
        itemProduceId: null,
        itemCode: null,
        processId: null,
        userId: null,
        createTime: [],
      },
      // 选中工单
      activeMo: undefined,
      // 工艺选项
      processOptions: undefined,
      // 检验结论选项
      inspectOptions: [],
      // 品号关联检验项
      entryList: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        code: [{ required: true, message: "检验单号不能为空", trigger: "blur" }],
        factoryId: [{ required: true, message: "工厂不能为空", trigger: "blur" }],
        schemeId: [{ required: true, message: "检验方案ID不能为空", trigger: "blur" }],
        planId: [{ required: true, message: "生产计划不能为空", trigger: "blur" }],
        moId: [{ required: true, message: "生产工单不能为空", trigger: "blur" }],
        moCode: [{ required: true, message: "生产工单不能为空", trigger: "blur" }],
        reportId: [{ required: true, message: "生产报工不能为空", trigger: "blur" }],
        itemId: [{ required: true, message: "产品ID不能为空", trigger: "blur" }],
        itemProduceId: [{ required: true, message: "产品生产ID不能为空", trigger: "blur" }],
        processId: [{ required: true, message: "工序ID不能为空", trigger: "blur" }],
        inspectAmount: [{ required: true, message: "检测数量不能为空", trigger: "blur" }],
        qualifiedAmount: [{ required: true, message: "合格数量不能为空", trigger: "blur" }],
        unqualifiedAmount: [{ required: true, message: "不合格数量不能为空", trigger: "blur" }],
        inspectResult: [{ required: true, message: "检测结果不能为空", trigger: "change" }],
        userId: [{ required: true, message: "检测人不能为空", trigger: "blur" }],
        inspectTime: [{ required: true, message: "检测时间不能为空", trigger: "blur" }],
      }
    };
  },
  created() {
    this.getList();
    this.getDict();
  },
  watch: {
    'form.moId': {
      handler(val) {
        this.getMoFun(val);
      },
    }
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true;
      // 执行查询
      getInspectProcessPage(this.queryParams).then(response => {
        this.list = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    /* 获取字典 */
    getDict() {
      this.inspectOptions = this.getDictDatas(this.DICT_TYPE.QMS_INSPECT_RESULT)
    },
    /* 查询检验方案 */
    getInspectScheme(itemId){
      getInspectSchemeByItem(itemId, 2).then(response => {
        const data = response.data;
        if (data != null) {
          this.entryList = data.entryList;
          this.form.schemeId = data.id;
          this.form.schemeName = data.name;
          this.form.schemeCode = data.code;
          this.form.inspectType = data.inspectType;
        }else {
          this.entryList = [];
          this.form.schemeId = undefined;
          this.form.schemeName = undefined;
          this.form.schemeCode = undefined;
          this.form.inspectType = undefined;
        }
      })
    },
    /* 查询生产工单 */
    async getMoFun(id) {
      if (id!=0){
        await getMoInfo(id).then(response => {
          const data = response.data;
          console.log(data)
          this.form.routes = data.routes;
          this.form.planId = data.planId;
          this.form.moId= data.id;
          this.form.moCode = data.code;
          this.form.factoryId = data.factoryId;
          this.form.factoryName = data.factoryName;
          this.form.itemCode = data.itemCode;
          this.form.itemName = data.itemName
          this.form.itemSpec = data.spec;
          this.form.drawCode = data.drawCode;
          this.form.itemId = data.itemId;
          this.form.itemProduceId = data.itemProduceId;
        })
        this.getInspectScheme(this.form.itemId);
      }
    },
    /* 查询生产工单 */
    selectMoQuery(data) {
      this.queryParams.moId= data.id;
      this.queryParams.moCode = data.code;
    },
    /* 查询生产工单 */
    selectMo(data) {
      this.form.moId = data.id;
      this.form.processId = undefined;
      this.entryList = [];
      this.loadEntryList(this.entryList);
    },
    /* 查询产品信息 */
    selectItemProduce(data) {
      this.queryParams.itemProduceId = data.id;
      this.queryParams.itemCode = data.itemCode;
    },
    /* 工艺变更事件 */
    changeProcess(row) {
      const data = this.entryList.filter(item => {
        return item.processId == row;
      })
      this.loadEntryList(data);
    },
    loadEntryList(data){
      this.load = true;
      this.form.entryList = data
      this.load = false;
    },
    /* 实际检验值改变事件 */
    changeReality(obj) {
      obj.inspectResult = 1;
      if (obj != null && obj != undefined && obj.reality != null && obj.reality != undefined && obj.standard !=null && obj.standard != undefined) {
        if (obj.standardUp != null && obj.standardUp != undefined && obj.reality > (obj.standard+obj.standardUp)){
          obj.inspectResult = 2;
        }
        if (obj.standardDown != null && obj.standardDown != undefined && obj.reality < (obj.standard-obj.standardDown)){
          obj.inspectResult = 2;
        }
      }
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        code: undefined,
        factoryId: undefined,
        schemeId: undefined,
        planId: undefined,
        moId: 0,
        moCode: undefined,
        reportId: undefined,
        itemId: undefined,
        itemProduceId: undefined,
        itemName: undefined,
        itemCode: undefined,
        itemSpec: undefined,
        drawCode: undefined,
        processId: undefined,
        processName: undefined,
        processCode: undefined,
        inspectAmount: undefined,
        qualifiedAmount: undefined,
        unqualifiedAmount: undefined,
        inspectResult: undefined,
        userId: undefined,
        inspectTime: undefined,
        remark: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加过程检验";
      this.refresh = new Date().getTime();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id;
      getInspectProcess(id).then(response => {
        this.form = response.data
        this.$set(this.form, 'routes', response.data.routes)
        this.open = true;
        this.title = "修改过程检验";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (!valid) {
          return;
        }
        // 校验数量
        if (Number(this.form.inspectAmount) != (Number(this.form.qualifiedAmount) + Number(this.form.unqualifiedAmount))) {

          console.log()
          console.log(this.form.inspectAmount)
          console.log(this.form.qualifiedAmount)
          console.log(this.form.unqualifiedAmount)
          this.$modal.msgError("检验数必须等于合格数与不合格数之和")
          return;
        }
        // 修改的提交
        if (this.form.id != null) {
          updateInspectProcess(this.form).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.getList();
          });
          return;
        }
        // 添加的提交
        createInspectProcess(this.form).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          this.getList();
        });
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id;
      this.$modal.confirm('是否确认删除过程检验编号为"' + id + '"的数据项?').then(function() {
          return deleteInspectProcess(id);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      // 处理查询参数
      let params = {...this.queryParams};
      params.pageNo = undefined;
      params.pageSize = undefined;
      this.$modal.confirm('是否确认导出所有过程检验数据项?').then(() => {
          this.exportLoading = true;
          return exportInspectProcessExcel(params);
        }).then(response => {
          this.$download.excel(response, '过程检验.xls');
          this.exportLoading = false;
        }).catch(() => {});
    }
  }
};
</script>
